package com.rh.number.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

import com.rh.number.enums.SystemRole;

@Setter
@Data
@Entity
@Table(name = "userinfo",  // 对应数据库表名
        uniqueConstraints = @UniqueConstraint(columnNames = "username"))
public class UserinfoEntity implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "用户名不能为空")
    @Size(min = 3, max = 50, message = "用户名长度需在3-50个字符")
    @Column(nullable = false, length = 50, unique = true)
    private String username;

    @NotBlank(message = "密码不能为空")
    @Size(min = 6, message = "密码至少需要6个字符")
    @Column(nullable = false, length = 100)
    @JsonIgnore
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;

    @Column(nullable = false)
    private Integer role;// 确保使用完整枚举类型

    // JPA 需要无参构造
    public UserinfoEntity() {}

    // 带参构造
    public UserinfoEntity(String username, String password, Integer role) {
        this.username = username;
        this.password = password;
        this.role = role;
    }

    public Map<String, Object> toSafeMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", this.id);
        map.put("username", this.username);
        map.put("role", this.role);
        return map;
    }

    // Getters & Setters
    public Long getId() { return id; }

    public void setId(Long id) {this.id = id;}
    public void setUsername(String username) { this.username = username; }

    @JsonProperty("password") // 明确指定JSON字段映射
    public void setPassword(String password) {
        this.password = password;
    }
    public void setRole(Integer role) { this.role = role; }


    @Override
    public String getUsername() { return username; }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return List.of();
    }

    @Override
    public String getPassword() { return password; }

    public Integer getRole() { return role; }


    @Override
    public boolean isAccountNonExpired() { return true; }

    @Override
    public boolean isAccountNonLocked() { return true; }

    @Override
    public boolean isCredentialsNonExpired() { return true; }

    @Override
    public boolean isEnabled() { return true; }


    // 角色枚举
    public enum SystemRole {
        NORMAL_USER,
        ADMIN_USER,
        AUDIT_USER;

        public GrantedAuthority toAuthority() {
            return () -> "ROLE_" + name();
        }
    }

}